﻿using DotNetCore.CAP;
using FreeSql;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Microsoft.VisualBasic;
using System.Collections.Generic;
using System.Text.Json;
using System.Transactions;

namespace Darius.API.Application.Commands.Order
{
    /// <summary>
    /// 订单创建
    /// </summary>
    public class OrderCreateHandler : IRequestHandler<OrderCreateCommand, Result>
    {
        private readonly IBaseRepositorys<SaleOrders> saleOrdersRepository;
        private readonly IBaseRepositorys<OrderDetails> OrderDetailsRepository;
        private readonly ILogger<OrderCreateHandler> logger; 
		private readonly ICapPublisher _capBus; ///消息队列

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="saleOrdersRepository"></param>
		/// <param name="OrderDetailsRepository"></param>
		/// <param name="logger"></param>
		public OrderCreateHandler(IBaseRepositorys<SaleOrders> saleOrdersRepository, IBaseRepositorys<OrderDetails> OrderDetailsRepository, ILogger<OrderCreateHandler> logger,  ICapPublisher capBus)
        {
            this.saleOrdersRepository = saleOrdersRepository;                         
            this.OrderDetailsRepository = OrderDetailsRepository;
            this.logger = logger; 
            _capBus = capBus;
        }
        /// <summary>
        /// 下订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(OrderCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            var res = 0;
            var orderNo = "";// 订单号

			try
            {
                //往订单表插入数据
                var saleOrder = new SaleOrders()
                {
                    OrderNo=request.OrderNo,
                    OrderNotes = request.OrderNotes,
                    CreateName = request.CreateName,
                    CreateDate = DateTime.Now,
                };
                if (request.OrderNo == "")
                {
                     orderNo = GenerateId1();

					saleOrder.OrderNo = orderNo;
                }
                res += saleOrdersRepository.Add(saleOrder);

                //往订单详情表插入数据
                foreach (var item in request.OrderDetails)
                {
                    var list1 = saleOrdersRepository.GetAll().Select(x => x.OrderId).ToList();                   
                    int a = list1.Max();
                    var list2 = OrderDetailsRepository.GetAll().Select(x => x.OrderDetailId).ToList();
                    int b = list2.Max();
                    int c = b +1;
                    var orderDetails = new OrderDetails()
                    {
                        OrderId = a,
                        ProductNumber = item.ProductNumber,
                        WorkOrder = saleOrder.OrderNo+"-"+c++,
                        ProductNum = item.ProductNum,
                        IsDeleted = item.IsDeleted,
                    };
                    res += OrderDetailsRepository.Add(orderDetails);
                }
                result.Messege = "订单创建成功";
                result.Code = res;
                logger.LogInformation("订单创建成功");



				//发布消息  

				#region 
				var saleOrderslist = saleOrdersRepository.GetAll().FirstOrDefault(c => c.OrderNo == orderNo);//获取订单数据
				var orderDetailsList = OrderDetailsRepository.GetAll().Where(c => c.OrderId == saleOrderslist.OrderId);

				var list = new List<WorkDataDto>();
				foreach (var item in orderDetailsList)
				{
					var OrderShopDto = new WorkDataDto()
					{
						WorkSheetNumber = item.WorkOrder,
						ProductNumber = item.ProductNumber,
						Numberofpackages = item.ProductNum,//计划数
						ScheduledStartTime = new DateTime(2024, 1, 1, 8, 0, 0),
						ScheduledEndTime = new DateTime(2024, 1, 1, 17, 0, 0),
						StartTime = null,
						EndTime = null,
						State = WorkSheetState.未开始, // 替换为实际枚举值
						Remark = saleOrderslist.OrderNotes,
						TaskIds = "1,2",
						ProductRelatedDocuments = orderNo,
					};
					//追加到集合中
					list.Add(OrderShopDto);
				}
				string PublishInformation = JsonSerializer.Serialize(list);
				IDictionary<string, string> dicHeader = new Dictionary<string, string>();
				dicHeader.Add(key: "One", value: PublishInformation);

				_capBus.Publish(name: "RabbitMQ.Order-WorkSheet", contentObj: saleOrderslist, headers: dicHeader);
				#endregion

				return result;




            }
            catch (Exception ex)
            {
                logger.LogError(ex, "订单创建失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "订单创建失败" };
            }

        }


        /// 前缀
        /// </summary>
        private static readonly string prefix1 = "XSDD";
        /// <summary>
        /// 销售订单号
        /// </summary>
        /// <param name="counter"></param>
        /// <returns></returns>
        public  string GenerateId1()
        {
            string datetimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
            Random random = new Random();
            int num = random.Next(1, 4);
            string Num = prefix1 + datetimeStr+"000"+num;
            return Num;
        }
    }
}

